package com.wowudi.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wowudi.entity.Department;
import com.wowudi.entity.Role;
import com.wowudi.entity.UserRole;
import com.wowudi.dto.Result;
import com.wowudi.mapper.DepartmentMapper;
import com.wowudi.mapper.RoleMapper;
import com.wowudi.mapper.UserRoleMapper;
import org.apache.ibatis.annotations.Options;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wowudi.mapper.UserMapper;
import com.wowudi.entity.User;
import com.wowudi.service.UserService;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private DepartmentMapper departmentMapper;


    /**
    * Description: 登录<br/>
    * date: 2022-3-14<br/>
    * @author 贺同志<br/>
    */
    @Override
    public Result login(String name, String pwd) {
        // 根据用账号和密码查询用户信息
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",name).eq("password",pwd);
        User user = userMapper.selectOne(wrapper);

        Result result = new Result();

        HashMap<String, Object> hashMap = new HashMap<>();
        if (user != null){
            // 获取该用户的角色
            List<Role> roleList = roleMapper.selectRoleByUserId(user.getUserId());
            List<String> roles = new ArrayList<>();
            roleList.forEach(role -> {
                roles.add(role.getRoleName());
            });
            hashMap.put("user",user);
            hashMap.put("roles",roles);
        }else{
            hashMap.put("user",null);
            hashMap.put("roles",null);
            result.setCode(500);
        }
        result.setData(hashMap);

        return result;
    }



    /**
    * Description: 修改用户信息<br/>
    * date: 2022-3-14<br/>
    * @author 贺同志<br/>
    */
    @Override
    public Result updateUser(User user) {
        int i = userMapper.updateById(user);
        int delete = userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id",user.getUserId()));
        user.getRoles().forEach(role -> {
            int insert = userRoleMapper.insert(new UserRole(user.getUserId(), role));
        });

        Result result = new Result();
        result.setMessage(i==0?"操作繁忙，请稍后再试！":"修改成功！");
        return result;
    }

    /**
    * Description: 查询所有用户信息<br/>
    * date: 2022-3-15<br/>
    * @author 贺同志<br/>
    */
    @Override
    public Result findPageUser(String userName,Integer currentPage,Integer limit) {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("user_name",userName).eq("del_flag",0);

        Page<User> page = new Page<>(currentPage,limit);
        Page<User> pageUser = userMapper.selectPage(page, wrapper);

        Result result = new Result();
        if (pageUser != null){
            pageUser.getRecords().forEach(user -> {
                List<Role> roleList = roleMapper.selectRoleByUserId(user.getUserId());
                String roles = "";
                ArrayList list = new ArrayList();
                for (int i = 0; i < roleList.size(); i++) {
                    roles += roleList.get(i).getRoleName()+",";
                    list.add(roleList.get(i).getId());
                }
                Department department = departmentMapper.selectOne(new QueryWrapper<Department>().eq("dp_id",user.getDeptId()));
                if (roles.length()!=0){
                    user.setRole(roles.substring(0,roles.length()-1));
                }
                user.setRoles(list);
                user.setDeptName(department.getDpName());
            });
            result.setData(pageUser);
            result.setMessage("查询成功!");
        }else{
            result.setMessage("操作繁忙，请稍后再试！!");
        }
        return result;
    }

    /**
    * Description: 新增用户<br/>
    * date: 2022-3-17<br/>
   * @author 贺同志<br/>
    */

    @Override
    @Options(useGeneratedKeys = true,keyColumn = "user_id",keyProperty = "id")
    public Result addUser(User user) {
        int i = userMapper.insert(user);
        user.getRoles().forEach(roleId -> {
            UserRole userRole = new UserRole(user.getUserId(), roleId);
            int userRoleId = userRoleMapper.insert(userRole);
        });
        Result result = new Result();
        result.setMessage(i==1?"新增用户成功！":"系统繁忙！");
        return result;
    }


    /**
    * Description: 删除用户·<br/>
    * date: 2022-3-17<br/>
    * @author 贺同志<br/>
    */
    @Override
    public Result deleteUser(Integer userId) {
        int i = userMapper.deleteById(userId);
        Result result = new Result();
        result.setMessage(i==1?"删除成功！":"系统繁忙！");
        return result;
    }


    /**
    * Description: 修改头像<br/>
    * date: 2022-3-28<br/>
    * @author 贺同志<br/>
    */
    @Override
    public int updateAvatar(long userId, String avatar) {
        User user = new User();
        user.setUserId(userId);
        user.setAvatar(avatar);
        int i = userMapper.update(user,new QueryWrapper<User>().eq("user_id",user.getUserId()));
        return i;
    }
}
